package cn.fx.fallbackprovider;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.cloud.netflix.zuul.filters.route.FallbackProvider;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.client.ClientHttpResponse;
import org.springframework.stereotype.Component;

/**
 * 服务调用失败触发熔断，返回提示信息
 */
@Component
public class PayServerFallback implements FallbackProvider {
    
    // 得到日志对象
    private final Logger logger = LoggerFactory.getLogger(FallbackProvider.class);

    // 指定要处理的服务。
    @Override
    public String getRoute() {
        return "*";  // pay-server应用名称 "*"代表所有服务都有作用
    }

    /**
     * @param route :服务的路由
     * @param cause ： 异常
     * @return ClientHttpResponse：熔断后的换回值
     */
    @Override
    public ClientHttpResponse fallbackResponse(String route, Throwable cause) {
        return new ClientHttpResponse() {
            @Override
            public HttpStatus getStatusCode() throws IOException {
                return HttpStatus.OK;
            }

            @Override
            public int getRawStatusCode() throws IOException {
                return 200;
            }

            @Override
            public String getStatusText() throws IOException {
                return "OK";
            }

            @Override
            public void close() {

            }

            @Override
            public InputStream getBody() throws IOException {
                return new ByteArrayInputStream("抱歉，服务不可用".getBytes());
            }

            @Override
            public HttpHeaders getHeaders() {
                HttpHeaders headers = new HttpHeaders();
                headers.setContentType(MediaType.APPLICATION_JSON);
                return headers;
            }
        };
    }
}